package com.cooldatasoft.domain.daoImpl;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cooldatasoft.domain.dao.GenericDao;

public class GenericDaoImpl<T, ID extends Serializable> extends HibernateDaoSupport implements GenericDao<T, ID> {

	private Class<T> persistentClass;

	private static final Log log = LogFactory.getLog(GenericDaoImpl.class);

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return getHibernateTemplate().findByCriteria(
				DetachedCriteria.forClass(persistentClass));
	}

	@SuppressWarnings("unchecked")
	public ID insert(T value) {
		ID id = null;

		id = (ID) getHibernateTemplate().save(value);
		if (log.isDebugEnabled()) {
			log.debug("inserting document: " + value);
		}

		return id;
	}

	public void update(T value) {
		getHibernateTemplate().saveOrUpdate(value);
		if (log.isDebugEnabled()) {
			log.debug("updating document: " + value);
		}
	}

	public void delete(T value) {
		getHibernateTemplate().delete(value);
		if (log.isDebugEnabled()) {
			log.debug("deleting document: " + value);
		}
	}

	public void delete(ID id) {
		T value = getById(id);
		if (value != null) {
			getHibernateTemplate().delete(value);
			if (log.isDebugEnabled())
				log.debug("deleting document: " + value + " by ID:" + id);
		}
	}

	public T getById(ID id) {
		return (T) getHibernateTemplate().get(persistentClass, id);
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	public void setPersistentClass(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

}
